//
//  ViewController.m
//  HelloIOSECGSDK
//
//  Created by FEI DENG on 7/1/14.
//  Copyright (c) 2014 FEI DENG. All rights reserved.
//

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

@synthesize ecgLineView;
@synthesize sdkVersionLabel;
@synthesize heartRateLabel;
@synthesize robustHeartRateLabel;
@synthesize r2rIntervalLabel;
@synthesize hrvLabel;
@synthesize heartBeatCountLabel;
@synthesize rpeakDetectedLabel;
@synthesize moodLabel;
@synthesize heartAgeLabel;
@synthesize stressLabel;
@synthesize signalQualityLabel;
@synthesize overallSignalQualityLabel;
@synthesize processDemo;

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view, typically from a nib.
}

- (void)viewWillAppear:(BOOL)animated
{
    [processDemo setEnabled:YES];
    [processDemo setTitle:@"ProcessRawDataFile" forState:UIControlStateNormal];
    
    tglibECG = [[TGLibECG alloc] init];
    [tglibECG setDelegate:self];
    sdkVersionLabel.text = [NSString stringWithFormat:@"SDK Version:%@",[tglibECG getVersion]];
    NSLog(@"ECG SDK Version: %@",[tglibECG getVersion]);
}

- (void)resetECG {
    [tglibECG resetECGAnalysis];
    [tglibECG setHRVOutputInterval:30];
    [tglibECG setMoodOutputPoint:30];
    [tglibECG enableNSLogMessages:false];
    [tglibECG setHeartAgeOutputPoint:30];
    [tglibECG setHeartAgeRecordNumber:5];
    [tglibECG setHeartAgeParameters:@"Mary" withAge:30 withPath:@""];
    [tglibECG setStressParameters:@"Mary" withGender:true withAge:30 withHeight:170 withWeight:65 withPath:@""];
    [tglibECG setStressOutputInterval:30];

    heartRateLabel.text = @"HeartRate:";
    robustHeartRateLabel.text = @"RobustHeartRate:";
    r2rIntervalLabel.text = @"r2rInterval:";
    heartBeatCountLabel.text = @"HeartBeatCount:";
    rpeakDetectedLabel.text = @"RpeakDetected:";
    hrvLabel.text = @"HRV:";
    moodLabel.text = @"Mood:";
    heartAgeLabel.text = @"HeartAge:";
    stressLabel.text = @"Stress:";
    signalQualityLabel.text = @"SignalQuality:";
    overallSignalQualityLabel.text = @"OverallSignalQuality:";
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dataReceived:(NSDictionary *)data {
    
    if([data valueForKey:dicECGheartRate])
    {
        heartRate = [[data valueForKey:dicECGheartRate] intValue];
        NSString *hrStr = [NSString stringWithFormat:@"HeartRate:%d",heartRate];
        heartRateLabel.text = hrStr;
        NSLog(@"ECGHeartRate  ======  %d",heartRate);
    }
    if([data valueForKey:dicECGrobustHeartRate])
    {
        robustHeartRate = [[data valueForKey:dicECGrobustHeartRate] intValue];
        NSString *robusthrStr = [NSString stringWithFormat:@"RobustHeartRate:%d",robustHeartRate];
        robustHeartRateLabel.text = robusthrStr;
        NSLog(@"ECGRobustHeartRate  ======  %d",robustHeartRate);
    }
    if([data valueForKey:dicECGr2rInterval]) {
        r2rInterval = [[data valueForKey:dicECGr2rInterval] intValue];
        NSString *rrIntStr = [NSString stringWithFormat:@"r2rInterval:%d",r2rInterval];
        r2rIntervalLabel.text = rrIntStr;
        NSLog(@"ECGr2rInt  ======  %d",r2rInterval);
        
        heartBeatCount = [tglibECG getTotalRRintNum];
        NSString *hbCountStr = [NSString stringWithFormat:@"HeartBeatCount:%d",heartBeatCount];
        heartBeatCountLabel.text = hbCountStr;
        NSLog(@"ECGHeartBeatCount  ======  %d",heartBeatCount);
    }
    if([data valueForKey:dicECGrpeakDetected])
    {
        rpeakDetected = [[data valueForKey:dicECGrpeakDetected] intValue];
        if (rpeakDetected == 1) {
            NSString *rpeakStr = [NSString stringWithFormat:@"RpeakDetected:%d",rpeakDetected];
            rpeakDetectedLabel.text = rpeakStr;
            NSLog(@"ECGRpeakDetected  ======  %d",rpeakDetected);
        }
    }
    if([data valueForKey:dicECGhrv]) {
        HRV = [[data valueForKey:dicECGhrv ] intValue];
        NSString *hrvStr = [NSString stringWithFormat:@"HRV:%d",HRV];
        hrvLabel.text = hrvStr;
        NSLog(@"ECGHRV  ======  %d",HRV);
    }
    if ([data valueForKey:dicECGsmoothedWave]) {
        [ecgLineView addValue:[[data valueForKey:dicECGsmoothedWave ] intValue]];
        //NSLog(@"ECG Smoothed Raw  ======  %d",[[data valueForKey:@"smoothedWave" ] intValue]);
    }
    if ([data valueForKey:dicECGmood]) {
        mood = [[data valueForKey:dicECGmood] intValue];
        NSString *moodStr = [NSString stringWithFormat:@"Mood:%d",mood];
        moodLabel.text = moodStr;
        NSLog(@"ECGMood  ======  %d",mood);
    }
    if ([data valueForKey:dicECGheartAge]) {
        heartAge = [[data valueForKey:dicECGheartAge] intValue];
        NSString *heartAgeStr = [NSString stringWithFormat:@"HeartAge:%d",heartAge];
        heartAgeLabel.text = heartAgeStr;
        NSLog(@"ECGHeartAge ======  %d",heartAge);
    }
    if ([data valueForKey:dicECGstress]) {
        stress = [[data valueForKey:dicECGstress] intValue];
        NSString *stressStr = [NSString stringWithFormat:@"Stress:%d",stress];
        stressLabel.text = stressStr;
        NSLog(@"ECGStress ======  %d",stress);
    }
    
}

- (void)exceptionECGMessage:(ECGException)excepType {
    //NSLog(@"Exceptions: %lu",(unsigned long)excepType);
    if (excepType == ECG_NO_SUCH_FILE) {
        NSLog(@"ECG_NO_SUCH_FILE");
    }
    else if(excepType == ECG_NOT_ENOUGH_DATA) {
        NSLog(@"ECG_NOT_ENOUGH_DATA");
    }
    else if (excepType == ECG_VALID_HEART_AGE) {
        NSLog(@"ECG_VALID_HEART_AGE");
    }
    else if (excepType == ECG_HAERT_AGE_HAS_INITIALIZED) {
        NSLog(@"ECG_HAERT_AGE_HAS_INITIALIZED");
    }
    else if (excepType == ECG_STRESS_HAS_INITIALIZED) {
        NSLog(@"ECG_STRESS_HAS_INITIALIZED");
    }
    else if (excepType == ECG_INVALID_INPUT_AGE) {
        NSLog(@"ECG_INVALID_INPUT_AGE");
    }
    else if (excepType == ECG_INVALID_INPUT_HEIGHT) {
        NSLog(@"ECG_INVALID_INPUT_HEIGHT");
    }
    else if (excepType == ECG_INVALID_INPUT_WEIGHT) {
        NSLog(@"ECG_INVALID_INPUT_WEIGHT");
    }
    else if (excepType == ECG_INVALID_INPUT_HEARTAGE_OUTPUTPOINT) {
        NSLog(@"ECG_INVALID_INPUT_HEARTAGE_OUTPUTPOINT");
    }
    else if (excepType == ECG_INVALID_INPUT_HEARTAGE_RECORDNUMBER) {
        NSLog(@"ECG_INVALID_INPUT_HEARTAGE_RECORDNUMBER");
    }
    else if (excepType == ECG_INVALID_INPUT_STRESS_OUTPUTPOINT) {
        NSLog(@"ECG_INVALID_INPUT_STRESS_OUTPUTPOINT");
    }
    else if (excepType == ECG_INVALID_INPUT_HRV_OUTPUTPOINT) {
        NSLog(@"ECG_INVALID_INPUT_HRV_OUTPUTPOINT");
    }
    else if (excepType == ECG_INVALID_INPUT_MOOD_OUTPUTPOINT) {
        NSLog(@"ECG_INVALID_INPUT_MOOD_OUTPUTPOINT");
    }
    else if (excepType == ECG_INVALID_INPUT_SIGNAL_QUALITY_THRESHOLD) {
        NSLog(@"ECG_INVALID_INPUT_SIGNAL_QUALITY_THRESHOLD");
    }
}


- (IBAction)onProcessRawDataFileClicked:(id)sender {
    NSLog(@"ProcessDataFileClicked");
    [processDemo setTitle:@"ProcessingData..." forState:UIControlStateNormal];
    [processDemo setEnabled:NO];
    [self resetECG];
    [self sendRawFromFile];
}

-(void)sendRawFromFile{
    rawArray = [[NSArray alloc] init];
    rawIndex = 1;
    rawNum = 0;
    NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *filePath = [mainBundle pathForResource:@"RawSample" ofType:@"txt"];
    NSString *contents = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    if (contents == nil) {
        
    }else{
        rawArray = [contents componentsSeparatedByString:@"\n"];
    }
    sendDataTimer = [NSTimer scheduledTimerWithTimeInterval:0.002 target:self selector:@selector(sendRawdata) userInfo:nil repeats:YES];
}

-(void)sendRawdata{
    
    if ([rawArray[rawIndex] hasPrefix:@"#"]) {
        // ignore the comment lines
        NSLog(@"DataFileComment: %@",rawArray[rawIndex++]);
    }
    else {
        //fill raw into SDK
        [tglibECG requestECGAnalysis:[[rawArray objectAtIndex:rawIndex] integerValue] withPoorSignal:200];
        rawNum++;
        //get signal quality every 512 raw sample
        if(rawNum % 512 == 0) {
            signalQuality = [tglibECG getSignalQuality];
            NSString *signalQualityStr = [NSString stringWithFormat:@"SignalQuality: %d",signalQuality];
            signalQualityLabel.text = signalQualityStr;
            NSLog(@"ECGSignalQuality: %d",signalQuality);
        }
    }
    
    if (rawIndex < rawArray.count - 1) {
        rawIndex ++;
    }else{
        [sendDataTimer invalidate];
        //get overall signal quality for the whole measurement
        overallSignalQuality = [tglibECG getOverallSignalQuality];
        NSString *overallSignalQualityStr = [NSString stringWithFormat:@"OverallSignalQuality: %f",overallSignalQuality];
        overallSignalQualityLabel.text = overallSignalQualityStr;
        NSLog(@"ECGOverallSignalQuality: %f",overallSignalQuality);
        [processDemo setEnabled:YES];
        [processDemo setTitle:@"ProcessRawDataFile" forState:UIControlStateNormal];

    }
}

@end
